package com.ruoyi.hr.controller.hr;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.hr.domain.Authority;
import com.ruoyi.hr.domain.Companys;
import com.ruoyi.hr.domain.Departments;
import com.ruoyi.hr.service.AuthorityService;
import com.ruoyi.hr.service.CompanysService;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@Controller
@RequestMapping("/sysAuthority")
public class SysAuthorityController extends BaseController {

    @Autowired
    AuthorityService authorityService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private CompanysService companysService;

    private String prefix = "hr/authority";

    /**
     * 跳转分页页面
     */
    @GetMapping()
    public String user() {
        return prefix + "/authority";
    }

    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list() {
        List<Authority> authorities = authorityService.getAuthority();
        for (Authority authority : authorities) {
            //先找公司名称
            authority.setCompName(getCompName(authority.getCompID()));
            //再找部门名称
            authority.setDepName(getDepName(authority));
            if(authority.getIsAdmin() != null){
                authority.setIsAdmin("是");
            }
        }
        startPage();
        return getDataTable(authorities);
    }

    /**
     * 新增权限
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {
        List<SysUser> sysUsers = authorityService.getUserList();
        List<Companys> companys = companysService.findAllCompanys(null);
        mmap.put("sysUsers", sysUsers);
        mmap.put("companys", companys);
        return prefix + "/add";
    }

    /**
     * 新增用户权限
     */
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated Authority authority) {
        if ("true".equals(authority.getIsAdmin())) {
            //设置成管理员
            return toAjax(authorityService.setUpAdmin(authority));
        } else {
            if ("true".equals(authority.getIsSelection())) {
                //管理下级
                //调用存储过程拿到某公司的所有下级公司
                String allId = authorityService.getSubordinateCompId(authority.getCompID());
                //分割字符串
                String[] arry = allId.split(",");
                Authority authority1 = new Authority();
                authority1.setUserId(authority.getUserId());
                int num = 0;
                for (String compId : arry) {
                    authority1.setCompID(Integer.parseInt(compId));
                    authority1.setDepIds(authorityService.getDepId(authority1));
                    num += authorityService.insertAuthority(authority1);
                }
                return toAjax(num);
            } else {
                if ("所有部门".equals(authority.getDepIds())) {
                    //获取这个公司所有的部门
                    authority.setDepIds(authorityService.getDepId(authority));
                }
                return toAjax(authorityService.insertAuthority(authority));
            }
        }
    }

    /**
     * 权限页面跳转
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap) {
        //取到这一条记录的用户、公司、部门权限
        Authority authority = authorityService.getAuthorityId(id);
        //取所有用户
        List<SysUser> sysUsers = authorityService.getUserList();
        //取所有公司
        List<Companys> companys = companysService.findAllCompanys(null);
        //取当前权限下的拥有的部门
        List<Departments> departments = getDepList(authority.getDepIds());
        mmap.put("sysUsers", sysUsers);
        mmap.put("companys", companys);
        mmap.put("departments", departments);
        mmap.put("authority", authority);
        return prefix + "/edit";
    }

    /**
     * 修改权限
     */
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated Authority authority) {
        return toAjax(authorityService.updateAuthority(authority));
    }

    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        try {
            return toAjax(authorityService.deleteAuthority(ids));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 列出权限列表时使用，用于翻译权限表中的公司id
     *
     * @param compID
     * @return
     */
    private String getCompName(Integer compID) {
        return authorityService.getCompName(compID);
    }

    /**
     * 列出权限列表时使用，用于翻译权限表中的部门id
     *
     * @param authority
     * @return
     */
    private String getDepName(Authority authority) {
        return authorityService.getDepName(authority);
    }

    /**
     * 取出某一条权限的部门集合
     */
    private List<Departments> getDepList(String depIds) {
        return authorityService.getDepList(depIds);
    }

    /**
     * 校验
     */
    @PostMapping("/check")
    @ResponseBody
    public int check(String type, String userId) {
        if ("setUpAdmin".equals(type)) {
            //设置管理员时,不能有任何权限
            return authorityService.findAuthorityCount(userId);
        }
        return 0;
    }
}
